define(['url', 'template', 'jquery','cookie'], (url, template) => {
  class Header {
    constructor () {
      this.loadHTML().then(() => {
        this.calcCartCount()
        this.userLogin()
        this.userLogout()
      })
    }
    loadHTML () {
      return new Promise(resolve => {
        $('header').load('/html/modules/header.html', resolve)
        $('footer').load('/html/modules/footer.html', resolve)
      })
    }
    calcCartCount () {
      // 从localStorage里把数据取出来计算总数量
      let cart = localStorage.getItem('cart')
      if (cart) {
        cart = JSON.parse(cart)
        const totalCount = cart.reduce((count, shop) => count + Number(shop.count), 0)
        $('#shopNum').html(totalCount)
        $('#cart span').html(totalCount)
      }
    }
    userLogin(){
      $('#headerLogin').hide()
      const userName = $.cookie('userName')
      if(userName){
        $('#headerLogin').show()
        $('#headerLogout').hide()
        $('#name').html(userName)
      }
    }
    userLogout(){
      $('#logout').on('click',function(){
        $.cookie('userName', "",{ expires: -1, path: '/' })
        $('#headerLogin').hide()
        $('#headerLogout').show()
      })
    }
  }
  return new Header()
})
